package com.example.controller.sys;

import com.example.common.Message;
import com.example.common.RedisUtils;
import com.example.common.UUIDUtils;
import com.example.model.ums.UmsAdmin;
import com.example.model.ums.UmsMenu;
import com.example.model.vo.UmsAdminInfo;
import com.example.model.vo.UmsAdminVo;
import com.example.model.vo.UmsMenuVo;
import com.example.service.ums.UmsAdminService;
import com.example.service.ums.UmsMenuService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sys/umsAdmin")
@Slf4j
public class UmsAdminController {

    @Autowired
    private UmsAdminService service;

    @Autowired
    private BCryptPasswordEncoder cryptPasswordEncoder;

    @Autowired
    private UmsMenuService umsMenuService;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 获取登录用户信息
     */
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public Message userInfo(){
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.userInfo ,start by startTime ->{}", startTime);
        //从Spring Secutity上下文中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(null == authentication){
            return Message.error(500,"用户信息获取失败!");
        }
        //获取用户信息
        UmsAdminVo umsAdminVo = (UmsAdminVo)authentication.getPrincipal();
        UmsMenuVo vo = new UmsMenuVo();
        vo.setAdminId(umsAdminVo.getId());
        List<UmsMenu> umsMenuByAdminId = umsMenuService.findUmsMenuByAdminId(vo);
        //返回的菜单集合
        List<UmsMenu> restList = new ArrayList<>();
        for (UmsMenu item: umsMenuByAdminId) {
            //等于null说明是一级菜单
            if(item.getParentId() == null){
                //有一级菜单去查询所有子菜单
                UmsMenu umsMenu = new UmsMenu();
                umsMenu.setParentId(item.getId());
                List<UmsMenu> umsMenusByParam = umsMenuService.findUmsMenusByParam(umsMenu);
                item.setMenus(umsMenusByParam);
                restList.add(item);
            }
        }
        UmsAdminInfo umsAdminInfo = new UmsAdminInfo(umsAdminVo.getUsername(), umsAdminVo.getIcon(), umsAdminVo.getNickName(), restList);
        log.info("UmsAdminController.userInfo 耗时：{} ms", System.currentTimeMillis() - startTime);
        return Message.ok(umsAdminInfo);

    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Message logout(HttpServletRequest request, HttpServletResponse response){
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.logout,start by startTime ->{}", startTime);
        //获取token信息
        String token = request.getHeader("token");
        //如果头部中没有携带token，则从参数中获取
        if(ObjectUtils.isEmpty(token)){
            //从参数中获取token信息
            token = request.getParameter("token");
        }
        //从Spring Secutity上下文对象中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //判断用户信息是否为空，如果不为空，则需要清空用户信息
        if(null != authentication){
            //清楚用户信息
            new SecurityContextLogoutHandler().logout(request,response,authentication);
            //删除redis中的token信息
            redisUtils.del("token_"+token);
        }
        log.info("UmsAdminController.logout 耗时：{} ms", System.currentTimeMillis() - startTime);
        return Message.ok("用户退出成功");
    }



    /**
     * 条件集合查询
     * @param admin
     * @return
     */
    @RequestMapping(value = "/findUmsAdminsByParam", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('umsAdmin')")
    @ResponseBody
    public Message findUmsAdminsByParam(UmsAdminVo admin) {
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.findUmsAdminsByParam 入参 UmsAdminVo ->{},start by startTime ->{}", admin, startTime);
        PageInfo<UmsAdmin> umsAdminsByParam = service.findUmsAdminsByParam(admin);
        log.info("UmsAdminController.findUmsAdminsByParam 耗时：{} ms", System.currentTimeMillis() - startTime);
        System.out.println(UUIDUtils.getId());
        return Message.ok(umsAdminsByParam);
    }

    /**
     * 条件单条查询
     * @param admin
     * @return
     */
    @RequestMapping(value = "/findUmsAdminByParam", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('umsAdmin')")
    @ResponseBody
    public Message findUmsAdminByParam(UmsAdmin admin) {
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.findUmsAdminByParam 入参 UmsAdmin ->{},start by startTime ->{}", admin, startTime);
        UmsAdmin umsAdmins = service.findUmsAdminByParam(admin);
        log.info("UmsAdminController.findUmsAdminByParam 耗时：{} ms", System.currentTimeMillis() - startTime);
        return Message.ok(umsAdmins);
    }

    /**
     * 新增
     * @param admin
     * @return
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('umsAdmin')")
    public Message insert(@RequestBody @Valid UmsAdmin admin) {
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.insert 入参 UmsAdmin ->{},start by startTime ->{}", admin, startTime);
        try{
            service.insert(admin);

        }catch (Exception e){
            return Message.error(e.getMessage());
        }
        log.info("UmsAdminController.insert 耗时：{} ms", System.currentTimeMillis() - startTime);
        return Message.ok();
    }

    /**
     * 修改
     * @param admin
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('umsAdmin')")
    public Message update(@RequestBody UmsAdmin admin) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.update 入参 UmsAdmin ->{},start by startTime ->{}", admin, startTime);
        if (null == admin) {
            throw new Exception("参数异常.");
        }
        try{
            service.update(admin);

        }catch (Exception e){
            return Message.error(e.getMessage());
        }

        log.info("UmsAdminController.update 耗时：{} ms", System.currentTimeMillis() - startTime);
        return Message.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delById/{id}", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('umsAdmin')")
    public Message delById(@PathVariable("id") String id) throws Exception {
        long startTime = System.currentTimeMillis();
        log.info("UmsAdminController.delById 入参 id ->{},By merchantUser ->{},start by startTime ->{}", id,startTime);
        if (null == id) {
            throw new Exception("参数异常.");
        }
        int deleteById = service.deleteById(id);
        log.info("UmsAdminController.delById 耗时：{} ms", System.currentTimeMillis() - startTime);
        if(deleteById == 1){
            return Message.ok();
        }else {
            return Message.error(500,"删除失败");
        }
    }


}
